
def mainImap(d):
    '''Zapisuje wiadomosci email od daty d, zwraca liste plikow'''
    import imap
    ret = imap.mainImap(d)
    print ret
    return ret

def mainCsv():
    '''csv z dysku do bazy'''
    from msgparser import parseLines
    import os, model, datetime
    d = '../out/csv/'
    list = os.listdir(d)
    m = model.Message()
    m.msg = 'csv'
    m.date = datetime.datetime(2007, 4, 1)
    for x in list:
        print x
        f = open(d + x, 'r')
        s = f.readlines()
        account = parseLines(s, False)
        m.accounts.append(account)
        f.close()
    print m
    return m

def mainEmail(file):
    '''zwraca msg z maila'''
    from msgparser import readEmail
    f = open(file, 'r')
    s = f.read()
    f.close()
    ret = readEmail(s)
    return ret

def mainDb(t):
    '''msg t do bazy'''
    from database import dbInsert
    dbInsert(t)

def dateDb():
    '''zwraca ostatnia date'''
    from database import lastDate
    return lastDate()

def createDirTree():
    '''utworzenie struktury katalogow'''
    import os
    import conf

    paths = [conf.files['basedir'],
             conf.mail['basedir'],
             conf.database['basedir']]
    for path in paths:
        print 'in', path
        if not os.path.exists(path):
            os.mkdir(path)
            print 'mk', path

def createDb():
    '''utworzenie pustej bazy'''
    f = open('../schema.sql', 'r')
    sqls = f.read()
    f.close()
    import os
    import sqlite3, conf
    path = conf.database['dbfile']
    if os.path.exists(path):
        os.remove(path)

    conn = sqlite3.connect(path)
    c = conn.cursor()
    for sql in sqls.split(';'):
        s = sql.strip()
        c.execute(s)
    c.close()

def mainDir():
    '''maile z dysku do bazy'''
    import os
    d = '../out/mail/'
    list = os.listdir(d)
    for x in list:
        print x
        msg = mainEmail(d + x)
        mainDb(msg)
        print 'ok'

if __name__ == '__main__':
    print 'start'
#    import datetime
#    mainImap(datetime.date(2007, 5, 1))
#    createDirTree()
    createDb()
    msg = mainCsv()
    mainDb(msg)
    mainDir()
#    print msg
    print 'done'
